package com.systemservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.systemservice.mapper.LoginMapper;
import com.systemservice.mapper.UserInfoMapper;
import generator.domain.Login;
import generator.domain.Role;
import com.systemservice.service.RoleService;
import com.systemservice.mapper.RoleMapper;
import generator.domain.UserInfo;
import generator.support.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
* @author 杨健康
* @description 针对表【t_role】的数据库操作Service实现
* @createDate 2022-06-19 13:52:19
*/
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role>
    implements RoleService{

    @Autowired
    RoleMapper roleMapper;

    @Autowired
    UserInfoMapper userInfoMapper;

    @Autowired
    LoginMapper loginMapper;

    /**
     * 根据id删除身份
     */
    @Override
    public ResponseResult<Object> deleteRoleById(Integer id) {
        // 查看是否有人绑定的还是这个身份
        QueryWrapper<Login> userQw = new QueryWrapper<>();
        userQw.eq("user_role_id", id);
        List<Login> logins = loginMapper.selectList(userQw);
        if (!logins.isEmpty()){
            return new ResponseResult<>(400, "该角色还有用户关联，不允许删除");
        }
        if (roleMapper.deleteById(id) > 0){
            return new ResponseResult<>();
        }
        return new ResponseResult<>(400, "请检查该身份是否存在");
    }

    /**
     * 添加角色信息
     */
    @Override
    public ResponseResult<Object> addRole(Role role) {
        // 查询是否有重复
        QueryWrapper<Role> roleQw = new QueryWrapper<>();
        roleQw.eq("role_name", role.getRoleName());
        List<Role> roles = roleMapper.selectList(roleQw);
        if (!roles.isEmpty()){
            return new ResponseResult<>(400, "已存在该角色");
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        role.setRoleCreateTime(format.format(new Date()));
        if (roleMapper.insert(role) > 0){
            return new ResponseResult<>();
        }
        return new ResponseResult<>(400, "添加失败");
    }

    @Override
    public ResponseResult<Object> editRole(Role role) {
        // 查询是否有重复
        QueryWrapper<Role> roleQw = new QueryWrapper<>();
        roleQw.eq("role_name", role.getRoleName());
        List<Role> roles = roleMapper.selectList(roleQw);
        if (!roles.isEmpty()){
            return new ResponseResult<>(400, "已存在该角色");
        }
        if (roleMapper.updateById(role) > 0){
            return new ResponseResult<>();
        }
        return new ResponseResult<>(400, "修改失败");
    }

}




